<?php
/**
 * 城市区县
 *
 * User: kaikaic
 * Date: 2018/4/25
 * Time: 1:59
 */

namespace app\exam\service;

use service\BasicService;
use think\Db;

class CityService extends BasicService {

    const CITY_RECOMMAD_NUM = 4;

    public function init() {
        $this->dataTable = ['SystemArea'];
    }

    public function listAll() {
        return Db::name($this->dataTable[0])->select();
    }

    /**
     * 列出1-2级城市
     */
    public function listLevel2() {
        $records = Db::name($this->dataTable[0])->select();

        $size = count($records);
        $areaList = array();
        for ($i=0; $i<$size; $i++) {
            $temp = $records[$i];

            $id = $temp['area_id'];
            $pid = $temp['area_parent_id'];
            if (!isset($areaList[$pid])) {
                $parent = Db::name($this->dataTable[0])->where(['area_id'=>$pid])->find();
                if (!$parent) {
                    continue;
                }

                $areaList[$pid] = array();
                $areaList[$pid]['id'] = $parent['area_id'];
                $areaList[$pid]['name'] = $parent['area_name'];
                $areaList[$pid]['city'] = array();
            }
            $areaList[$pid]['city'][] = array('id'=>$temp['area_id'], 'name'=>$temp['area_name']);
        }

        return $areaList;
    }

    /**
     * 1-3级城市数组
     */
    public function listCityArray() {
        $records = Db::name($this->dataTable[0])->select();

        $areaList = $this->listTopLevel($records);


        foreach ($areaList as $k=>$v) {
            $areaList[$k]['city'] = $this->listSubLevel($records, $k);
        }

        return $areaList;
    }

    private function listTopLevel($areaList) {
        $size = count($areaList);

        $topLevel = array();
        for ($i=0; $i<$size; $i++) {
            $tmp = $areaList[$i];

            if (!$tmp['area_parent_id']) {
                $temp = array();

                $temp['id'] = $tmp['area_id'];
                $temp['name'] = $tmp['area_name'];
                $temp['city'] = array();

                $topLevel[$temp['id']] = $temp;
            }
        }

        return $topLevel;
    }

    private function listSubLevel($areaList, $parentID, $district=true) {
        $size = count($areaList);

        $subLevel = array();
        for ($i=0; $i<$size; $i++) {
            $tmp = $areaList[$i];

            if ($parentID == $tmp['area_parent_id']) {
                $temp = array();

                $temp['id'] = $tmp['area_id'];
                $temp['name'] = $tmp['area_name'];
                if ($district) {
                    $temp['district'] = $this->listSubLevel($areaList, $temp['id'], false);
                }

                $subLevel[] = $temp;
            }
        }

        return $subLevel;
    }

    /**
     * 当前排序最大值,新纪录自动+1
     */
    public function getMaxSort() {
        return Db::name($this->dataTable[0])->max('sort');
    }
}

